package com.douyu.ocean.messageSender;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.douyu.ocean.confLoader.ConnectMysql;


public class MessageSender {
	
	private static Logger log = LoggerFactory.getLogger(MessageSender.class);
	private String phoneNum = "";
	private String email = "";
	
	public boolean sendMessage(String funcType, String message) {
		
		log.warn("sending message :" + message);
		ArrayList<String> emailList = new ArrayList<String>();
		
		boolean status_sms = false;
		boolean status_email = false;
		SmsSender smsSender = new SmsSender();
		
		if(funcType.equals("local")){
			if(email != ""){
				emailList.add(email);
			}
			
			if(!phoneNum.isEmpty()){
				try{
					smsSender.sendSms(message, phoneNum);
				}catch (Exception e){
					e.printStackTrace();
				}
			}
			
		}else{
			List<Map<String, String>> contact = new ArrayList<Map<String, String>>();
			ConnectMysql getConn = new ConnectMysql();
			contact = getConn.getWatcher(funcType);
		
			
			for(Map<String, String> type : contact){
				if(type.containsKey("email")){
					emailList.add(type.get("email"));
				}
				if(type.containsKey("phoneNumber")){
				
					status_sms = false;
					try{
						for(int i=0; i<2 && !status_sms; i++){
							log.warn("sending message :"+ message +" with Sms");
							status_sms = smsSender.sendSms(message, type.get("phoneNumber"));
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}
		}
		
		EmailSender emailSender = new EmailSender();
		
		if(emailList.size() != 0){
			status_email = false;
			for(int i=0; i<2 && !status_email; i++){
				log.warn("sending message :"+ message +" with Email");
				status_email = emailSender.sendEmail(message, emailList);
			}
		}else{
			status_email = true;
			log.warn("there is no watcher need to send email");
		}
		
		return status_sms && status_email;
	}
	
	public void sendMessageToPhone(String message, String phoneNumber, String email){
		phoneNum = phoneNumber;
		this.email = email;
		sendMessage("local",message);
	}
	public static void main(String[] args){
		MessageSender tmp = new MessageSender();
		tmp.sendMessage("redis", "testForJava");
	}
	
}
